layui.define(['form'], function (exports) {
    "use strict";
    var form = layui.form;

    // 记录弹窗的index的变量
    top.layer._indexTemp = top.layer._indexTemp || {};
    // 优化select的选项在某些场景下的显示问题
    $(document).on('click'
        , '.layui-table-view .layui-select-title, .layui-layer-content .layui-select-title, .select_option_in_layer .layui-select-title, .xm-select-title'
        , function (event) {
            layui.stope(event);
            var that = this;
            // return;
            top.layer.close(top.layer._indexTemp['selectInTable']);
            var titleElem = $(this);
            if (!titleElem.parent().hasClass('layui-form-selected')&&!titleElem.parent().hasClass('xm-form-selected')) {
                return;
            }
            var dlElem = titleElem.next();
            var selectElem = titleElem.parent().prev();
            var dlClone = dlElem.clone(true);

            function getDlPosition() {
                var titleElemPosition = getPosition(titleElem);
                var topTemp = titleElemPosition.top;
                var leftTemp = titleElemPosition.left;
                if (titleElem.parent().hasClass('layui-form-selectup')) {
                    topTemp = topTemp - dlElem.outerHeight() + titleElem.outerHeight() - parseFloat(dlElem.css('bottom'));
                } else {
                    topTemp += parseFloat(dlElem.css('top'));
                }
                // console.log(topTemp, leftTemp);
                return {
                    top: topTemp,
                    left: leftTemp
                };
            }

            var dlPosition = getDlPosition();

            titleElem.css({backgroundColor: 'transparent'});
            top.layer._indexTemp['selectInTable'] = top.layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shade: 0,
                anim: -1,
                fixed: top !== window,
                isOutAnim: false,
                // offset: [topTemp + 'px', leftTemp + 'px'],
                offset: [dlPosition.top + 'px', dlPosition.left + 'px'],
                // area: [dlElem.outerWidth() + 'px', dlElem.outerHeight() + 'px'],
                area: dlElem.outerWidth() + 'px',
                content: $(that).hasClass('xm-select-title') ? '<div class="xm-select-parent"></div>' : '<div class="layui-unselect layui-form-select layui-form-selected layui-table-select"></div>',
                success: function (layero, index) {
                    dlElem.appendTo(layero.find('.layui-layer-content').css({overflow: 'hidden'}).find('.layui-form-selected'));
                    layero.width(titleElem.width());
                    layero.find('dl dd').click(function () {
                        top.layer.close(index);
                    });
                },
                end: function () {
                    // 简单粗暴处理，直接form.render掉
                    layui.each(selectElem, function (index, elem) {
                        elem = $(elem);
                        var elemP = elem.parent();
                        var formFlag = elemP.hasClass('layui-form');
                        var filterTemp = elemP.attr('lay-filter');
                        // mark一下当前的
                        formFlag || elemP.addClass('layui-form');
                        filterTemp || elemP.attr('lay-filter', 'tablePlug_form_filter_temp_' + new Date().getTime() + '_' + Math.floor(Math.random() * 100000));
                        // 将焦点集中到要渲染的这个的容器上
                        form.render(type, elemP.attr('lay-filter'));
                        // 恢复现场
                        formFlag || elemP.removeClass('layui-form');
                        filterTemp || elemP.attr('lay-filter', null);
                    });
                }
            });
        });


    // 点击document的时候如果不是下拉内部的就关掉该下拉框的弹窗
    $(document).on('table.select.dl.hide', function (event, elem) {
        // 只有在layui的table内部的选项的点击才需要阻止layer关闭
        // if ($(elem).closest('.layui-form-select').length && $(elem).closest('.layui-table-view').length) {
        // // if ($(elem).closest('.layui-form-select').length) {
        //   return;
        // }
        top.layer.close(top.layer._indexTemp['selectInTable']);
    });

    // 点击document的时候触发
    $(document).on('click', function (event) {
        $(document).trigger('table.select.dl.hide', this.activeElement);
    });

    // 窗口resize的时候关掉表格中的下拉
    $(window).on('resize', function (event) {
        $(document).trigger('table.select.dl.hide', this.activeElement);
    });

    // 监听滚动在必要的时候关掉select的选项弹出（主要是在多级的父子页面的时候）
    $(document).scroll(function () {
        if (top !== window && parent.parent) {
            // 多级嵌套的窗口就直接关掉了
            top.layer.close(top.layer._indexTemp['selectInTable'])
        }
    });


    // 获得某个节点的位置
    function getPosition(elem, _window) {
        _window = _window || window;
        var $ = _window ? _window.layui.$ : layui.$;
        var offsetTemp = {};
        if (parent !== window) {
            if (!parent.layui.selectEnhance) {
                console.log('该功能必须依赖tablePlug请先引入');
            } else {
                offsetTemp = parent.layui.selectEnhance.getPosition($(window.frames.frameElement), parent);
            }
        }
        var bodyOffset = $('body').hasClass('layui-container') ? $('body').offset() : {top: 0, left: 0};
        return {
            top: (offsetTemp.top || 0) + elem.offset().top - bodyOffset.top - $(_window.document).scrollTop(),
            left: (offsetTemp.left || 0) + elem.offset().left - bodyOffset.left - $(_window.document).scrollLeft()
        }
    }

    exports('selectEnhance', {getPosition:getPosition});
});